<?php

include "../../../lib/start.php";

check_session();
check_permission(DOC_PERM);

ini_set("display_errors)", "1");

header("Content-type: text/plain");

// verifico se il record e' gia' presente
$sel = "SELECT * FROM lettura_circolari WHERE id_circolare = ".$_REQUEST['idc']." AND docente = ".$_SESSION['__user__']->getUid();
try{
	$res = $db->executeQuery($sel);
} catch (MySQLException $ex){
	print "ko#".$ex->getMessage()."#".$ex->getQuery();
	exit;
}
$subtract_unread = false;

if($res->num_rows > 0){
	$row = $res->fetch_assoc();
	if($row['letta'] == 0)
		$subtract_unread = true;
	$query = "UPDATE lettura_circolari SET letta = 1, data_lettura = NOW() WHERE id_circolare = ".$_REQUEST['idc']." AND docente = ".$_SESSION['__user__']->getUid();
}
else{
	$query = "INSERT INTO lettura_circolari (id_circolare, docente, letta, data_lettura) VALUES (".$_REQUEST['idc'].", ".$_SESSION['__user__']->getUid().", 1, NOW())" ;
	$subtract_unread = true;
}
try{
	$result = $db->executeQuery($query);
} catch(MySQLException $ex){
	print "ko#".$ex->getMessage()."#".$ex->getQuery();
	exit;
}

if($subtract_unread)
	$_SESSION['__unread_count__']--;
$res = "ok#".$_SESSION['__unread_count__'];
	
print $res;
exit;

?>